import http from './request.js';

class GroupManagement {
    constructor() {
        this.searchInput = document.getElementById('searchInput');
        this.searchButton = document.getElementById('searchButton');
        this.groupTable = document.getElementById('groupTable').getElementsByTagName('tbody')[0];
        this.groupContainer = document.getElementById('groupContainer');
        this.createGroupBtn = document.querySelector('.createGroup');
        
        // Modal elements
        this.editModal = document.getElementById('editModal');
        this.createModal = document.getElementById('createModal');
        this.editForm = document.getElementById('editForm');
        this.createForm = document.getElementById('createForm');
        
        this.currentPage = 1;
        this.loading = false;
        this.hasMore = true;
        this.lastKeyword = '';

        this.filterCheckboxes = document.querySelectorAll('.filter-options input[type="checkbox"]');

        // 初始化搜索相关变量
        this.currentKeyword = '';
        this.selectedTypes = [];

        this.init();
    }

    init() {
        this.loadGroups();
        this.bindEvents();
    }

    bindEvents() {
        // 搜索事件
        this.searchButton.addEventListener('click', () => {
            this.handleSearch();
        });

        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });

        // 滚动加载
        this.groupContainer.addEventListener('scroll', () => {
            this.handleScroll();
        });

        // 创建群组按钮
        this.createGroupBtn.addEventListener('click', () => {
            this.showCreateModal();
        });

        // 表单提交事件
        this.editForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleEdit();
        });

        this.createForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleCreate();
        });

        // 关闭模态框
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.addEventListener('click', () => {
                this.closeModals();
            });
        });

        // 使用事件委托处理按钮点击
        this.groupTable.addEventListener('click', (e) => {
            const target = e.target;
            if (target.matches('.edit-btn')) {
                const groupId = target.dataset.groupId;
                this.editGroup(groupId);
            } else if (target.matches('.delete-btn')) {
                const groupId = target.dataset.groupId;
                this.deleteGroup(groupId);
            } else if (target.matches('.join-btn')) {
                const groupId = target.dataset.groupId;
                this.joinGroup(groupId);
            } else if (target.matches('.exit-btn')) {
                const groupId = target.dataset.groupId;
                this.leaveGroup(groupId);
            }
        });

        // 为所有Type复选框添加change事件监听器
        this.filterCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                this.handleSearch();  // 当复选框状态改变时立即触发搜索
            });
        });
    }

    handleScroll() {
        if (this.loading || !this.hasMore) return;

        const { scrollTop, scrollHeight, clientHeight } = this.groupContainer;
        if (scrollHeight - scrollTop - clientHeight < 100) {
            this.currentPage++;
            this.loadGroups(this.lastKeyword, true);
        }
    }

    async loadGroups(keyword = '', append = false) {
        if (this.loading) return;
        
        try {
            this.loading = true;
            
            if (!append) {
                this.currentPage = 1;
                this.groupTable.innerHTML = '';
            }

            // 获取选中的类型
            const selectedTypes = Array.from(this.filterCheckboxes)
                .filter(cb => cb.checked)
                .map(cb => cb.value);

            // 构建请求参数
            const params = {
                keyword: keyword,
                // 将数组转换为逗号分隔的字符串
                types: selectedTypes.join(',')
            };

            const response = await http.get(`/groups/page/${this.currentPage}`, params);
            const groups = response.list || [];
            this.hasMore = groups.length === response.limit;
            this.lastKeyword = keyword;

            if (append) {
                this.appendGroups(groups);
            } else {
                this.renderGroups(groups);
            }
        } catch (error) {
            console.error('Failed to load groups:', error);
            alert(error.message);
        } finally {
            this.loading = false;
        }
    }

    async handleSearch() {
        const keyword = this.searchInput.value.trim();
        await this.loadGroups(keyword);
    }

    renderGroups(groups) {
        if (!Array.isArray(groups)) {
            console.error('Invalid groups data:', groups);
            return;
        }
        
        this.groupTable.innerHTML = this.generateGroupRows(groups);

        if (groups.length === 0) {
            this.groupTable.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align: center;">No groups found</td>
                </tr>
            `;
        }
    }

    appendGroups(groups) {
        if (!Array.isArray(groups) || groups.length === 0) return;
        
        const newRows = this.generateGroupRows(groups);
        this.groupTable.insertAdjacentHTML('beforeend', newRows);
    }

    generateGroupRows(groups) {
        const currentUserId = http.getUserInfo()?.id;
        
        return groups.map(group => `
            <tr>
                <td>${group.GroupName}</td>
                <td>${group.Description || '-'}</td>
                <td>${group.Type}</td>
                <td>${group.AdminName}</td>
                <td>${group.MemberCount + 1}</td>
                <td>${group.Privacy}</td>
                <td>
                    ${parseInt(group.AdminID) === currentUserId ? 
                        // 当前用户是群组管理员
                        `<button class="edit-btn" data-group-id="${group.GroupID}">Edit</button>
                         <button class="del-btn" data-group-id="${group.GroupID}">Delete</button>` 
                    : 
                        // 当前用户不是管理员，判断是否已加入
                        group.IsMember ? 
                            `<button class="exit-btn" data-group-id="${group.GroupID}">Leave</button>` 
                        : 
                            `<button class="join-btn" data-group-id="${group.GroupID}">Join</button>`
                    }
                </td>
            </tr>
        `).join('');
    }

    async handleEdit() {
        const formData = {
            name: document.getElementById('groupName').value,
            description: document.getElementById('description').value,
            type: document.getElementById('type').value,
            privacy: document.getElementById('privacy').value,
        };

        const groupId = document.getElementById('groupId').value;

        try {
            await http.put(`/groups/${groupId}`, formData);
            this.editModal.style.display = 'none';
            this.loadGroups(); // 重新加载列表
            alert('Group updated successfully!');
        } catch (error) {
            console.error('Failed to update group:', error);
            alert(error.message);
        }
    }

    async handleCreate() {
        const formData = {
            name: document.getElementById('createGroupName').value,
            description: document.getElementById('createDescription').value,
            type: document.getElementById('createType').value,
            privacy: document.getElementById('createPrivacy').value,
        };

        try {
            await http.post('/groups', formData);
            this.closeModals();
            alert('Group created successfully!');
            await this.loadGroups(); // 重新加载列表
        } catch (error) {
            console.error('Failed to create group:', error);
            alert(error.message);
        }
    }

    showCreateModal() {
        // 清空表单
        this.createForm.reset();
        // 显示模态框
        this.createModal.style.display = 'block';
    }

    async editGroup(groupId) {
        try {
            const group = await http.get(`/groups/${groupId}`);
            document.getElementById('groupId').value = groupId;
            document.getElementById('groupName').value = group.GroupName;
            document.getElementById('description').value = group.Description;
            document.getElementById('type').value = group.Type;
            document.getElementById('privacy').value = group.Privacy;
            this.editModal.style.display = 'block';
        } catch (error) {
            console.error('Failed to get group details:', error);
            alert(error.message);
        }
    }

    async deleteGroup(groupId) {
        if (!confirm('Are you sure you want to delete this group?')) {
            return;
        }

        try {
            await http.delete(`/groups/${groupId}`);
            alert('Group deleted successfully!');
            this.loadGroups(); // 重新加载列表
        } catch (error) {
            console.error('Failed to delete group:', error);
            alert(error.message);
        }
    }

    async joinGroup(groupId) {
        try {
            await http.post(`/groups/${groupId}/join`);
            alert('Joined group successfully!');
            this.loadGroups(); // 重新加载列表
        } catch (error) {
            console.error('Failed to join group:', error);
            alert(error.message);
        }
    }

    async leaveGroup(groupId) {
        try {
            await http.post(`/groups/${groupId}/leave`);
            alert('Left group successfully!');
            this.loadGroups(); // 重新加载列表
        } catch (error) {
            console.error('Failed to leave group:', error);
            alert(error.message);
        }
    }

    closeModals() {
        this.editModal.style.display = 'none';
        this.createModal.style.display = 'none';
    }
}

// 在编辑模态框打开时渲染成员列表
async function renderMembers(groupId) {
    try {
        const group = await http.get(`/groups/${groupId}`);
        const membersList = document.getElementById('membersList');
        
        if (group.Members && group.Members.length > 0) {
            membersList.innerHTML = group.Members.map(member => `
                <div class="member-item">
                    <img class="member-avatar" src="${member.Photo || '../assets/images/default_photo.jpg'}" alt="Member Avatar">
                    <span class="member-name">${member.Name}</span>
                </div>
            `).join('');
        } else {
            membersList.innerHTML = '<p>No members yet</p>';
        }
    } catch (error) {
        console.error('Failed to load members:', error);
        membersList.innerHTML = '<p>Failed to load members</p>';
    }
}

// 在打开编辑模态框时调用
function openEditModal(group) {
    // 现有的编辑模态框代码...
    
    // 渲染成员列表
    renderMembers(group.GroupID);
    
    editModal.style.display = "block";
}

// 创建实例
new GroupManagement();
  